#include "Poco/Semaphore.h"
#include "Poco/Exception.h"
#include "BSemaphore.h"

using namespace SystemTool;

// Construct the obj
BSemaphore::BSemaphore(int iCurCnt) : m_iCurCnt(iCurCnt)
{
    m_pSemaphore = new Poco::Semaphore(iCurCnt);
    for (size_t index = 0; index < m_iCurCnt; index++)
    {
       Release();
    }
}

// Destruct the obj
BSemaphore::~BSemaphore()
{
    for (size_t index = 0; index < m_iCurCnt; index++)
    {
       Release();
    }

    Poco::Semaphore *pSemaphore = (Poco::Semaphore *)m_pSemaphore;
    if (pSemaphore)
    {
        delete pSemaphore;
        m_pSemaphore = nullptr;
    }
}

// Wait for the event to be signal
void BSemaphore::Acquire(long lMs)
{
    Poco::Semaphore* pSemaphore = (Poco::Semaphore*)m_pSemaphore;
    if(pSemaphore == nullptr)
    {
        return;
    }

    if(lMs == 0)
    {
        pSemaphore->wait();
        return;
    }

    try
    {
       pSemaphore->wait(lMs);
    }
    catch(Poco::Exception& e)
    {
        // Do nothing for timeout
    }
}

// Set the event to signal
void BSemaphore::Release()
{
    Poco::Semaphore* pSemaphore = (Poco::Semaphore*)m_pSemaphore;
    if(pSemaphore)
    {
        pSemaphore->set();
    }
}
